package com.hly.musicbackground.config;

import com.hly.musicbackground.Utils.FileUtils;
import com.hly.musicbackground.Utils.PathUtils;
import com.hly.musicbackground.filter.IPHandlerInterceptor;
import com.hly.musicbackground.filter.VersionHandlerInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@EnableWebMvc
public class WebMvcConfig  implements WebMvcConfigurer {

    private final VersionHandlerInterceptor versionHandlerInterceptor;
    private final IPHandlerInterceptor ipHandlerInterceptor;
    private final PathUtils pathUtils;

    /**
     * 拦截器配置
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(ipHandlerInterceptor)
                .addPathPatterns("/api/**").order(0);
        registry.addInterceptor(versionHandlerInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns(
                        "/api/version/**"
                ).order(1);
    }

    /**
     * 添加静态资源文件，外部可以直接访问地址
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 创建项目需要的文件夹
        FileUtils.files(pathUtils.path, new String[]{pathUtils.filePath, pathUtils.imagesPath});

        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler(pathUtils.resourcesPath + "/**")
                .addResourceLocations("file:" + pathUtils.path.replace("\\","/") + "/");
    }
}
